const bcrypt = require('bcryptjs')

const { getUserInfo } = require('../service/user.service')
const { userFormateError,
        userAlreadyExited,
        userLoginError,
        invalidPassword,
        userDoesNotExist } = require('../constant/err.type')

// 用户名和密码不能为空
const userValidator = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    if (!user_name || !password) {
        console.error("用户名和密码为空!", ctx.request.body);
        ctx.app.emit('error', userFormateError, ctx);

        return
    }
    await next()
}


// 验证用户是否存在
const userAuthentication = async (ctx, next) => {
    const { user_name } = ctx.request.body

    if (await getUserInfo({ user_name })) {
        console.error('用户已存在!');
        ctx.app.emit('error', userAlreadyExited, ctx);

        return
    }
    await next()
}

// 加密
const cryptPassword = async (ctx, next) => {
    const { password } = ctx.request.body

    const salt = bcrypt.genSaltSync(10) // 加盐 次数为10
    const hash = bcrypt.hashSync(password, salt) // 保存为密文

    ctx.request.body.password = hash

    await next()
}

// 验证用户登录
const verifylogin = async (ctx, next) => {
    const { user_name, password } = ctx.request.body;

    try {
        const res = await getUserInfo({user_name})
        if(!res){
            console.error('用户名不存在',ctx.request.body);
            ctx.app.emit('error',userDoesNotExist,ctx)
            return
        }

        if (!bcrypt.compareSync(password, res.password)) {
            console.error('密码不正确', ctx.request.body);
            ctx.app.emit('error',invalidPassword,ctx)
            return  
        }
    } catch (err) {
        console.error('用户登录错误！');
        ctx.app.emit('error', userLoginError, ctx)
        return
    };
    
    await next()
}
module.exports = {
    userAuthentication,
    userValidator,
    cryptPassword,
    verifylogin
}


